    // Learn TypeScript:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/life-cycle-callbacks.html

import { RoomUser } from "../bean/GameBean";
import NickNameLabel from "../util/NickNameLabel";
import { Tools } from "../util/Tools";

const {ccclass, property} = cc._decorator;

@ccclass
export default class GamePlayerController extends cc.Component {

    @property(cc.Node)
    avatar: cc.Node = null;   //头像
   
    @property(cc.Label)
    nameLabel: cc.Label = null;  //用户昵称

    @property(cc.Node)
    playerTypeImage: cc.Node = null;  //玩家类型图片节点

    @property(cc.Node)
    disconnectNode: cc.Node = null;  //断线状态节点

    @property(cc.Node)
    leaveNode: cc.Node = null;  //退出状态节点

    @property(cc.Node)
    deathNode: cc.Node = null;  //死亡状态节点

    // 用户ID，用于标识这个头像预制体对应的用户
    private userId: string = "";

    // onLoad () {}

    start () {

    }

    setData(user: RoomUser){
        

        this.scheduleOnce(() => {
            if (user == null) {
               
                this.avatar.active = false;
                this.userId = "";
                // 清空时也隐藏所有状态节点
                this.initializeStatusNodes();
            } else {
                // 保存用户ID
                this.userId = user.userId;
                
                // 开局时隐藏所有状态节点
                this.initializeStatusNodes();

                // 检查必要的组件是否存在
                if (!this.avatar) {
                    console.error("avatar 节点未设置！");
                    return;
                }

                if (!this.nameLabel) {
                    console.error("nameLabel 节点未设置！");
                    return;
                }

                if (!this.playerTypeImage) {
                    console.error("playerTypeImage 节点未设置！");
                    return;
                }

                // 设置头像
                if (user.avatar && user.avatar.trim() !== '') {
                    

                    // 确保头像节点可见
                    this.avatar.active = true;
                    this.avatar.opacity = 255;

                    // 加载头像
                    Tools.setNodeSpriteFrameUrl(this.avatar, user.avatar);

                    // 延迟检查头像是否设置成功
                    this.scheduleOnce(() => {
                        const sprite = this.avatar.getComponent(cc.Sprite);
                        

                       
                    }, 1.0);
                } else {
                    console.warn("头像URL为空，隐藏头像节点");
                    this.avatar.active = false;
                }

                // 设置昵称
                if (user.nickName && user.nickName.trim() !== '') {
                    let nicknameLabel = this.nameLabel.getComponent(NickNameLabel);
                    if (nicknameLabel) {
                        nicknameLabel.string = user.nickName;
                      
                    } else {
                        // 如果没有NickNameLabel组件，直接设置Label
                        this.nameLabel.string = user.nickName;
                        
                    }
                } else {
                    console.warn("昵称为空");
                    if (this.nameLabel) {
                        this.nameLabel.string = "未知用户";
                    }
                }
            }
        }, 0.1);
    }

    /**
     * 设置玩家类型图像
     * @param playerType 玩家类型 (red, yellow, green, pink)
     */
    setPlayerTypeImage(playerType: string) {
        if (!this.playerTypeImage) {
            console.error("playerTypeImage 节点未设置！");
            return;
        }

        if (!playerType || playerType.trim() === '') {
            console.warn("玩家类型为空，隐藏类型图片");
            this.playerTypeImage.active = false;
            return;
        }

        // 显示类型图片节点
        this.playerTypeImage.active = true;

        // 根据playerType加载对应的图片资源
        const imagePath = `player_res/${playerType}`;
       
        
        cc.resources.load(imagePath, cc.SpriteFrame, (err, spriteFrame: cc.SpriteFrame) => {
            if (err) {
                console.error(`加载玩家类型图片失败: ${imagePath}`, err);
                this.playerTypeImage.active = false;
                return;
            }

            const sprite = this.playerTypeImage.getComponent(cc.Sprite);
            if (sprite) {
                sprite.spriteFrame = spriteFrame;
                
            } else {
                console.error("playerTypeImage 节点缺少 Sprite 组件");
            }
        });
    }

    /**
     * 只设置玩家类型图像，不生成动物预制体
     * @param playerType 玩家类型
     */
    setPlayerTypeImageOnly(playerType: string) {
        this.setPlayerTypeImage(playerType);
    }

    /**
     * 获取用户ID
     */
    getUserId(): string {
        return this.userId;
    }

    /**
     * 显示玩家状态节点
     * @param eventType 事件类型 (7-死亡, 8-断线, 9-退出, 10-重连)
     */
    showPlayerStatus(eventType: number): void {
        
        
        switch (eventType) {
            case 7: // 死亡
                this.showDeathStatus();
                break;
            case 8: // 断线
                this.showDisconnectStatus();
                break;
            case 9: // 退出
                this.showLeaveStatus();
                break;
            case 10: // 重连 - 隐藏断线状态
                this.hideDisconnectStatus();
                break;
            default:
                console.warn(`未知的玩家状态事件类型: ${eventType}`);
        }
    }

    /**
     * 根据OnlineStateEvent显示状态（用于断线重连）
     * @param onlineStateEvent OnlineStateEvent值 (7-死亡, 8-离线, 9-离开, 10-在线/重连)
     */
    showStatusByOnlineStateEvent(onlineStateEvent: number): void {
        
        
        // 先隐藏所有状态节点
        this.hideAllStatusNodes();
        
        switch (onlineStateEvent) {
            case 7: // 死亡
                this.showDeathStatus();
                break;
            case 8: // 离线
                this.showDisconnectStatus();
                break;
            case 9: // 离开
                this.showLeaveStatus();
                break;
            case 10: // 在线/重连
                // 不显示任何状态节点
                break;
            default:
                console.warn(`未知的OnlineStateEvent: ${onlineStateEvent}`);
        }
    }

    /**
     * 显示死亡状态
     */
    private showDeathStatus(): void {
        
        this.hideAllStatusNodes();
        if (this.deathNode) {
            this.deathNode.active = true;
            
        } else {
            console.error("deathNode 节点未设置！请在编辑器中设置deathNode");
        }
    }

    /**
     * 显示断线状态
     */
    private showDisconnectStatus(): void {
       
        // 根据优先级，如果已经显示退出状态，则不显示断线状态
        if (this.leaveNode && this.leaveNode.active) {
            
            return;
        }
        
        this.hideOtherStatusNodes('disconnect');
        if (this.disconnectNode) {
            this.disconnectNode.active = true;
          
        } else {
            console.error("disconnectNode 节点未设置！请在编辑器中设置disconnectNode");
        }
    }

    /**
     * 显示退出状态
     */
    private showLeaveStatus(): void {
       
        this.hideAllStatusNodes();
        if (this.leaveNode) {
            this.leaveNode.active = true;
           
        } else {
            console.error("leaveNode 节点未设置！请在编辑器中设置leaveNode");
        }
    }

    /**
     * 隐藏断线状态
     */
    public hideDisconnectStatus(): void {
        if (this.disconnectNode) {
            this.disconnectNode.active = false;
          
        }
    }

    /**
     * 隐藏所有状态节点
     */
    public hideAllStatusNodes(): void {
        if (this.disconnectNode) this.disconnectNode.active = false;
        if (this.leaveNode) this.leaveNode.active = false;
        if (this.deathNode) this.deathNode.active = false;
    }

    /**
     * 隐藏除指定类型外的其他状态节点
     * @param keepType 保持显示的状态类型
     */
    private hideOtherStatusNodes(keepType: 'disconnect' | 'leave' | 'death'): void {
        if (keepType !== 'disconnect' && this.disconnectNode) {
            this.disconnectNode.active = false;
        }
        if (keepType !== 'leave' && this.leaveNode) {
            this.leaveNode.active = false;
        }
        if (keepType !== 'death' && this.deathNode) {
            this.deathNode.active = false;
        }
    }

    /**
     * 初始化状态节点（隐藏所有状态节点）
     */
    initializeStatusNodes(): void {
        this.hideAllStatusNodes();
    }
    
    // update (dt) {}
}
